package api

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"xiaoniu-job/internal/beat"
	"xiaoniu-job/internal/biz"
	"xiaoniu-job/pkg"
)

// RunHandler 接受服务端的调度请求 执行一次任务 POST /run
func RunHandler(writer http.ResponseWriter, request *http.Request) {
	defer request.Body.Close()
	body, _ := ioutil.ReadAll(request.Body)
	var clientRequest pkg.ClientTaskRequest
	err := json.Unmarshal(body, &clientRequest)
	if err != nil {
		var response = pkg.NewFailResponse("请求体转换错误")
		marshal, _ := json.Marshal(response)
		writer.Write(marshal)
		return
	}
	runOnce, err := biz.RunOnce(&clientRequest)
	if err != nil {
		var response = pkg.NewFailResponse("任务执行异常")
		marshal, _ := json.Marshal(response)
		writer.Write(marshal)
		return
	}
	var response = pkg.NewSuccessResponse(runOnce)
	marshal, _ := json.Marshal(response)
	writer.Write(marshal)
}

// GetLogHandler 接受服务端的获取该次任务的执行结果 POST /getLog
func GetLogHandler(writer http.ResponseWriter, request *http.Request) {
	defer request.Body.Close()
	body, _ := ioutil.ReadAll(request.Body)
	var clientRequest pkg.ClientLogRequest
	err := json.Unmarshal(body, &clientRequest)
	if err != nil {
		var response = pkg.NewFailResponse("请求体转换错误")
		marshal, _ := json.Marshal(response)
		writer.Write(marshal)
		return
	}
	res, err := biz.GetLog(&clientRequest)
	if err != nil {
		var response = pkg.NewFailResponse("查询异常")
		marshal, _ := json.Marshal(response)
		writer.Write(marshal)
		return
	}
	var response = pkg.NewSuccessResponseWithData("查询成功", res)
	marshal, _ := json.Marshal(response)
	writer.Write(marshal)
}

// QueryLocalLogHandler 接受服务端的获取该次任务的本地执行日志 POST /queryLocalLog
func QueryLocalLogHandler(writer http.ResponseWriter, request *http.Request) {
	defer request.Body.Close()
	body, _ := ioutil.ReadAll(request.Body)
	var clientRequest pkg.ClientLogRequest
	err := json.Unmarshal(body, &clientRequest)
	if err != nil {
		var response = pkg.NewFailResponse("请求体转换错误")
		marshal, _ := json.Marshal(response)
		writer.Write(marshal)
		return
	}
	res, err := biz.QueryLocalLog(&clientRequest)
	if err != nil {
		var response = pkg.NewFailResponse("查询异常")
		marshal, _ := json.Marshal(response)
		writer.Write(marshal)
		return
	}
	var response = pkg.NewSuccessResponseWithData("查询成功", res)
	marshal, _ := json.Marshal(response)
	writer.Write(marshal)
}

// GracefulShutdownHandler 优雅停机接口
func GracefulShutdownHandler(writer http.ResponseWriter, _ *http.Request) {
	go func() {
		beat.StopHeartBeat()
		biz.StopConsumer()
	}()
	writer.Write([]byte("调用成功"))
}
